package com.zzzy.framework.aspect;

import com.zzzy.common.exception.WarningException;
import com.zzzy.common.util.JsonUtil;
import com.zzzy.common.util.ServletUtils;
import com.zzzy.framework.cache.RepeatSubmitCache;
import com.zzzy.framework.common.annotation.RepeatSubmit;
import com.zzzy.framework.common.util.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Description: 防止重复提交拦截器
 *
 * @author fc
 * @date 2024/4/28
 */
@Aspect
@Component
public class RepeatSubmitAspect {
    @Resource
    private RepeatSubmitCache repeatSubmitCache;

    @Before("@annotation(repeatSubmit)")
    public void before(JoinPoint joinPoint, RepeatSubmit repeatSubmit) {
        String token = SecurityUtils.getLoginUser().getToken();
        // 唯一标识（url + token）
        String cacheRepeatKey = ServletUtils.getRequest().getRequestURI() + token;
        long currentTimeMillis = System.currentTimeMillis();
        Map<String, Long> paramsMapCache = repeatSubmitCache.getCache(cacheRepeatKey);
        String paramsJson = JsonUtil.toJSONString(joinPoint.getArgs());
        if (!CollectionUtils.isEmpty(paramsMapCache)) {
            Long lastRequestTimeMillis = paramsMapCache.get(paramsJson);
            if (Objects.nonNull(lastRequestTimeMillis) && (currentTimeMillis - lastRequestTimeMillis) < repeatSubmit.interval()) {
                throw new WarningException(repeatSubmit.message());
            }
        }
        if (CollectionUtils.isEmpty(paramsMapCache)) {
            paramsMapCache = new HashMap<>();
        }
        paramsMapCache.put(paramsJson, currentTimeMillis);
        repeatSubmitCache.putCache(cacheRepeatKey, paramsMapCache);
    }
}
